package com.zhl.controller;

import com.zhl.entity.Role;
import com.zhl.entity.User;
import com.zhl.entity.ZhlResult;
import com.zhl.service_.RoleService;
import com.zhl.service_.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2018/11/6.
 */
@Controller
public class UserController {

    Logger logger = LoggerFactory.getLogger("UserController");

    @Autowired
    private UserService userService;

    @PostMapping("/dologin")
    @ResponseBody
    public ZhlResult login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        logger.info("username={},password={}",username,password);

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ) {
            return ZhlResult.build(400,"用户名或密码为空");
        }

        //使用shiro的认证登录
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //开始登录
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            User user = (User) subject.getPrincipal();
            request.getSession().setAttribute("user", user);
            return ZhlResult.ok(user);
        }catch (UnknownAccountException e){
            return ZhlResult.build(400,"用户名或密码错误!");
        }catch (LockedAccountException e){
            return ZhlResult.build(400,"账户被锁定!");
        }


    }

    @PostMapping("/pagelogin")
    public String pagelogin(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String flag = request.getParameter("flag");

        logger.info("username={},password={}",username,password);

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ) {
            model.addAttribute("msg","用户名或密码为空");
            return "login.html";
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //开始登录
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            User user = (User) subject.getPrincipal();
            request.getSession().setAttribute("user", user);
            if (flag != null && flag.equals("admin")) {
                return "redirect:/admin/index";
            }
            return "redirect:/index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名或密码错误");
        }catch (LockedAccountException e){
            model.addAttribute("msg","账户被锁定");
        }
        if (flag != null && flag.equals("admin")) {
            return "admin/login.html";
        }
        return "login.html";


    }


    //判断登录状态
    @RequestMapping("/is/login")
    @ResponseBody
    public ZhlResult isLogin(HttpServletRequest request) {

        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            return ZhlResult.build(400,"未登录状态");

        }else {
            return ZhlResult.ok(user);
        }

    }

    //登出
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {

        request.getSession().removeAttribute("user");
        return "index.html";

    }

    /**
     * 注册
     * @return
     */
    @PostMapping("/user/register")
    @ResponseBody
    public ZhlResult register(User user) {

        user.setAvailable(1);//目前默认可用
        logger.info("user={}",user.toString());

        //开始注册
        int i = userService.register(user);
        if (i > 0) {
            return ZhlResult.ok();

        }
        return ZhlResult.fail("注册失败");


    }



    //查询所有用户
    @RequestMapping("/api/user")
    @ResponseBody
    public ZhlResult userlist(HttpServletRequest request) {

        List<User> users = userService.userList();
        return ZhlResult.ok(users);

    }

    //根据id查询用户
    @RequestMapping("/api/setrole/{id}")
    public String userlist(@PathVariable("id") int id,Model model) {

        User userByid = userService.queryUserByid(id);
        List<Role> roles = userByid.getRoles();
        String rids = "";
        for (Role role:roles) {
            rids += role.getRid()+",";
        }
        userByid.setRids(rids);
        model.addAttribute("userByid",userByid);

        return "/admin/userdetail.html";

    }

    /**
     * 添加和修改用户的角色
     * @param id
     * @param rids
     * @return
     */
    @RequestMapping("/api/adduserrole")
    @ResponseBody
    public ZhlResult addRoleFunction(int id,String rids) {

        userService.addUserRole(id,rids);
        return ZhlResult.ok();

    }



}